import {
	Button,
	Collapse,
	Form,
	Input,
	Row,
	Col,
	Transfer,
	TreeSelect,
	message,
} from 'antd'
import React, {memo, useState, useEffect} from 'react'
import {history, connect} from 'umi'
import {
	getCompany,
	viewCompany,
	getCityList,
	updateCity,
	getParentMerchant,
} from '@/service/system/company'
import {translateDataToTree} from '@/utils/common/index'
import styles from '@/assets/common/css/page.less'

const fieldNames = {
	label: 'name',
	value: 'id',
	id: 'id',
	pId: 'parentId',
}

const {TextArea} = Input
const {Panel} = Collapse

const Share = memo((props: any) => {
	const [targetKeys, setTargetKeys] = useState<string[]>([])
	const [selectedKeys, setSelectedKeys] = useState<string[]>([])
	const [form] = Form.useForm()
	const [treeData, setTreeData] = useState<any[]>([])
	const [cityData, setCityData] = useState<any[]>([])
	// 获取上级组织
	const onCompanyFun = (merchantId: string) => {
		getCompany({merchantId}).then((res: any) => {
			if (res?.success) {
				const list = translateDataToTree(res.data)
				getParentMerchant({merchantId}).then((r: any) => {
					if (r?.data) {
						setTreeData([
							{
								...r.data,
								children: [...list],
							},
						] as any)
					} else {
						setTreeData(list)
					}
				})
			}
		})
	}
	console.log(treeData, 'treeData---')
	// 获取所有城市数据
	const onAllCityFun = (merchantId: string) => {
		getCityList({merchantId}).then((res: any) => {
			if (res.success) {
				setCityData([...res.data])
			}
		})
	}

	// 获取详情数据
	const onViewFun = (merchantId: string) => {
		viewCompany(merchantId).then((res: any) => {
			if (res?.success) {
				form.setFieldsValue({...res?.data})
				onAllCityFun(res?.data?.parentId)
			}
		})
	}

	// 获取回显城市数据
	const onCityFun = (merchantId: string) => {
		getCityList({merchantId}).then((res: any) => {
			if (res.success) {
				setTargetKeys([...res.data].map((item) => item.cityId))
			}
		})
	}

	// 穿梭框选中事件
	const onChange = (nextTargetKeys: any) => {
		setTargetKeys(nextTargetKeys)
	}

	// 穿梭框变化事件
	const onSelectChange = (
		sourceSelectedKeys: string[],
		targetSelectedKeys: string[],
	) => {
		setSelectedKeys([...sourceSelectedKeys, ...targetSelectedKeys])
	}

	// 表单提交
	const onFinish = async () => {
		const fromData = await form.validateFields()
		updateCity(fromData.id, {cityIds: targetKeys})
			.then((res: any) => {
				if (res.success) {
					message.success(res.msg)
					history.goBack()
				}
			})
			.catch((err) => {
				message.error(err)
			})
	}

	useEffect(() => {
		const {id} = props.location.query
		if (id) {
			onViewFun(id)
			onCityFun(id)
			onCompanyFun(id)
		}
	}, [])

	const customizeHeader = (value: string) => (
		<div>
			<div className={styles.tip} />
			{value}
		</div>
	)
	return (
		<div className={styles.page}>
			<div className={`${styles.content} ${styles.formDetils}`}>
				<Collapse
					defaultActiveKey={['1', '2']}
					ghost
					expandIconPosition="end">
					<Panel header={customizeHeader('基础信息')} key="1">
						<Form
							name="basic"
							form={form}
							layout="horizontal"
							labelCol={{style: {width: 80}}}
							initialValues={{remember: true}}
							autoComplete="off">
							<Row gutter={12}>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="编号"
										name="id"
										rules={[
											{
												required: true,
												message: '请输入编号',
											},
										]}>
										<Input
											placeholder="请输入编号"
											disabled
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="名称"
										name="name"
										rules={[
											{
												required: true,
												message: '请输入名称',
											},
										]}>
										<Input
											placeholder="请输入名称"
											disabled
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item
										label="上级组织"
										name="parentId"
										rules={[
											{
												required: true,
												message: '请输入上级组织',
											},
										]}>
										<TreeSelect
											showSearch
											style={{width: '100%'}}
											dropdownStyle={{
												maxHeight: 400,
												overflow: 'auto',
											}}
											placeholder="请选择部门"
											allowClear
											treeDefaultExpandAll
											fieldNames={fieldNames}
											treeDataSimpleMode
											treeData={treeData}
											disabled
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}>
									<Form.Item label="描述" name="description">
										<TextArea
											disabled
											placeholder="请输入（最多200个字）"
											autoSize={{minRows: 4, maxRows: 6}}
											maxLength={200}
										/>
									</Form.Item>
								</Col>
							</Row>
						</Form>
					</Panel>
					<Panel header={customizeHeader('分配城市')} key="2">
						<Row gutter={12}>
							<Col
								sm={{span: 24}}
								md={{span: 24}}
								lg={{span: 24}}>
								<Transfer
									dataSource={cityData}
									titles={['未选中的城市', '已选中的城市']}
									targetKeys={targetKeys}
									selectedKeys={selectedKeys}
									render={(item) => item.cityName!}
									rowKey={(record) => record.cityId}
									onChange={onChange}
									onSelectChange={onSelectChange}
								/>
							</Col>
						</Row>
					</Panel>
				</Collapse>
				<div className={styles.wrap}>
					<Button type="primary" htmlType="submit" onClick={onFinish}>
						保存
					</Button>
					<Button
						htmlType="reset"
						className="reset"
						onClick={(e) => {
							e.stopPropagation()
							history.goBack()
						}}>
						取消
					</Button>
				</div>
			</div>
		</div>
	)
})
export default connect(({global}: any) => ({global}))(Share)
